// .........................................................................
// Title: bond_betas.do
//
// Estimates betas of bonds with respect to a broad value-weighted index
// .........................................................................

* --------------------------------------
* Bond betas to value-weighted index
* --------------------------------------

* Construct benchmark returns
use "$tmp/trace_merged_panel_complete_m", clear
gsort cusip date_m
keep if inlist(rating_cat, "AAA", "AA", "A", "BBB")
gcollapse (mean) hedged_return net_return [aw = value_outstanding], by(date_m)
rename hedged_return benchmark_hedged_return
rename net_return benchmark_net_return
save "$tmp/benchmark_ig_returns_m", replace

* Compute rolling bond betas
use "$tmp/trace_merged_panel_complete_m", clear
keep if inlist(rating_cat, "AAA", "AA", "A", "BBB")
mmerge date_m using "$tmp/benchmark_ig_returns_m", unmatched(m)
drop _merge
gsort cusip date_m
foreach x in 3 6 12 24 36 {
    di "Processing betas at `x' months"   
    if `x' >= 12 {
        by cusip: asreg hedged_return benchmark_hedged_return, wind(date_m `x') min(12)
    }
    else {
        by cusip: asreg hedged_return benchmark_hedged_return, wind(date_m `x') min(0)
    }
    rename _b_benchmark_hedged_return beta`x'm
    rename _b_cons alpha`x'm
    rename _Nobs Nobs_beta`x'm
    winsor2 beta`x'm, cuts(1 99)
    winsor2 alpha`x'm, cuts(1 99)
    label var beta`x'm "Bond Beta (`x'M)"
    label var beta`x'm_w "Bond Beta (`x'M)"
    label var alpha`x'm "Bond Alpha (`x'M)"
    label var alpha`x'm_w "Bond Alpha (`x'M)"
    cap drop _*
}
keep cusip date_m beta* alpha* Nobs_*
save "$tmp/rolling_betas_m", replace
